import { Injectable } from '@nestjs/common';
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { CartEntity } from "./cart.entity";
import { ResultVo } from "../../vo/common/result.vo";
import { CartAddVo } from 'src/vo/cart/cart-add.vo';
import { CartDelVo } from 'src/vo/cart/cart-del.vo';
import { ApiCodeEnum } from 'src/enum/api-code.enum';
import { CartUpdateVo } from 'src/vo/cart/cart-update.vo';
import { ProductEntity } from '../product/product.entity';

@Injectable()
export class CartService {
    constructor(
        @InjectRepository(CartEntity)
        private readonly cartRepository: Repository<CartEntity>,

        @InjectRepository(ProductEntity)
        private readonly productRepository: Repository<ProductEntity>,
    ) { }

    async updateCart(cartUpdateVo: CartUpdateVo) {
        let product = await this.productRepository.findOne({ id: cartUpdateVo.productId })
        if (!product) {
            return ResultVo.exception(ApiCodeEnum.PRODUCT_NOT_EXIST)
        }
        if (cartUpdateVo.num == 0) {
            // 删除购物车
            const res = await this.cartRepository.delete({ productId: cartUpdateVo.productId, userId: cartUpdateVo.userId })
            return ResultVo.successWithData(res)
        }
        let date = new Date()
        let data = new CartEntity()
        data = { productId: cartUpdateVo.productId, productName: product.productName, productImg: product.headImg, num: cartUpdateVo.num, price: product.salePrice, userId: cartUpdateVo.userId, createdTime: date, updatedTime: date, id: null }
        // 查询该商品是否已经加入购物车
        let cart = await this.cartRepository.findOne({ userId: cartUpdateVo.userId, productId: cartUpdateVo.productId })
        if (cart) {
            console.log("购物车里已经存在该商品,直接更新库存");
            cart.num = cartUpdateVo.num
            cart.price = product.salePrice
            cart.productName = product.productName
            cart.productImg = product.headImg
            await this.cartRepository.update({ id: cart.id }, cart)
        } else {
            await this.cartRepository.save<CartEntity>(data)
        }
        return ResultVo.success()

    }

    async delCart(cartDelVo: CartDelVo) {
        let cart = await this.cartRepository.findOne({ id: cartDelVo.cartId })
        if (!cart) return ResultVo.fail("购物车数据异常!")
        let currentNum = cart.num - cartDelVo.num
        if (currentNum < 0) {
            return ResultVo.fail("购物车数量扣除异常!")
        } else if (currentNum == 0) {
            // 删除购物车
            await this.cartRepository.delete(cartDelVo.cartId)
        } else {
            // 更新购物车
            await this.cartRepository.update({ id: cartDelVo.cartId }, { num: currentNum })
        }
        return ResultVo.success()
    }

    async addCart(cartAddVo: CartAddVo) {
        console.log("添加购物车", cartAddVo);
        let date = new Date()
        let data = new CartEntity()
        data = { ...cartAddVo, createdTime: date, updatedTime: date, id: null }
        // 查询该商品是否已经加入购物车
        let cart = await this.cartRepository.findOne({ userId: cartAddVo.userId, productId: cartAddVo.productId })
        if (cart) {
            console.log("购物车里已经存在该商品,直接更新库存");
            cart.num += cartAddVo.num
            cart.price = cartAddVo.price
            cart.productName = cartAddVo.productName
            cart.productImg = cartAddVo.productImg
            await this.cartRepository.update({ id: cart.id }, cart)
        } else {
            await this.cartRepository.save<CartEntity>(data)
        }
        return ResultVo.success()
    }

    async queryAll() {
        let data = await this.cartRepository.find()
        return ResultVo.successWithData(data)
    }

    async queryOne(id: number | string) {
        let data = await this.cartRepository.findOne(id)
        return ResultVo.successWithData(data)
    }

    async add(data: CartEntity) {
        let date = new Date()
        data.createdTime = date
        data.updatedTime = date
        let res = await this.cartRepository.save<CartEntity>(data)
        return ResultVo.successWithData(res)
    }

    async edit(data: CartEntity) {
        data.updatedTime = new Date()
        let res = await this.cartRepository.update({ id: data.id }, data)
        return ResultVo.successWithData(res)
    }

    async delete(id: number | string) {
        let res = await this.cartRepository.delete(id)
        return ResultVo.successWithData(res)
    }
}
